/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package request.general;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "request_general")
@ViewScoped
public class Main extends Beans {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Find request_generalFind = new Find();
    private List<Beans> request_generalList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();
    private request.status.Main request_status = new request.status.Main();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {

            //Verifica si hay un registro seleccionado
            if (logged.getMasterId() == 0) {
                return;
            }

            map.clear();
            map.put("s.id = " + logged.getMasterId(), " ");

            request_generalList.clear();
            request_generalList = request_generalFind.byMap(map);

            setId(request_generalList.get(0).getId());
            setId_facultad(request_generalList.get(0).getId_facultad());
            setIdl_accion(request_generalList.get(0).getIdl_accion());
            getUniversityBeans().setId(request_generalList.get(0).getUniversityBeans().getId());
            setRecibido(request_generalList.get(0).getRecibido());
            setCarrera(request_generalList.get(0).getCarrera());
            setObservacion(request_generalList.get(0).getObservacion());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("id_facultad = " + getId_facultad(), " AND ");
            map.put("idl_accion = " + getIdl_accion(), " AND ");
            map.put("lower(carrera) = '" + getCarrera().toLowerCase() + "'", " ");

            if (request_generalFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.solicitud_general (id_recepcionista,idl_accion,recibido, registrado,id_facultad,carrera,observacion) "
                    + "VALUES (" + logged.getLoggedId() + ", " + getIdl_accion() + ",'" + getRecibido() + "',CURRENT_TIMESTAMP, " + getId_facultad()
                    + ", '" + getCarrera() + "', '" + getObservacion() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            request_generalList = request_generalFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setMasterId(request_generalList.get(0).getId());
            setId(logged.getMasterId());

            request_status.insert(logged.getMasterId(), 1, getRecibido(), logged.getLoggedId());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("s.id <> " + logged.getMasterId(), " AND ");
            map.put("id_facultad = " + getId_facultad(), " AND ");
            map.put("idl_accion = " + getIdl_accion(), " AND ");
            map.put("lower(carrera) = '" + getCarrera().toLowerCase() + "'", " ");

            if (request_generalFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.solicitud_general SET "
                    + "id_recepcionista = " + logged.getLoggedId() + ",  "
                    + "id_facultad = " + getId_facultad() + ", "
                    + "idl_accion  = " + getIdl_accion() + ", "
                    + "carrera = '" + getCarrera() + "',  "
                    + "observacion = '" + getObservacion() + "'  "
                    + "WHERE id =" + logged.getMasterId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            request_status.insert(logged.getMasterId(), 2, getRecibido(), logged.getLoggedId());

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());

            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Elimina el Usuario por id
        sql = "DELETE FROM public.solicitud_general "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void insertUniversity() throws Exc, SQLException, Exception {
        university.general.Main universidad = new university.general.Main();
        getUniversityBeans().setId(universidad.insert(getUniversityBeans().getNombre(), getUniversityBeans().getFundada(), getUniversityBeans().getDetalle()));
        getUniversityBeans().setNombre("");
        getUniversityBeans().setFundada(0);
        getUniversityBeans().setDetalle("");
    }

    public void insertFaculty() throws Exc, SQLException, Exception {
        university.faculty.Main faculty = new university.faculty.Main();
        getFacultyBeans().setId(faculty.insert(getFacultyBeans().getNombre(), getUniversityBeans().getId()));
        getFacultyBeans().setNombre("");
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
        logged.setMasterId(0);
        logged.setMasterName("");
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
